<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-3-16
 * Time: 15:42
 */

namespace zhtfrontend\components\bases;


use common\components\helpers\Fun;
use yii\web\BadRequestHttpException;
use yii\web\Controller;

class BaseController extends Controller{

    public $menu;

    public $menu_current;

    public function init(){
        \Yii::configure(\Yii::$app->authManager, [
            'db'=>Fun::getSiteDb(),
            'cacheKey'=>\Yii::$app->request->get('site').'_rabc'
        ]);



    }

    public function beforeAction( $action ){
        \Yii::configure(\Yii::$app->user, [
            'loginUrl'=>Fun::url(['site/login']),
        ]);
        $this->menu=Fun::cache('menu_branch_cache',false);
        $this->menu_current=Fun::getCurrentMenu($this->menu);
        $this_id=$this->menu_current['id'];

        $this->__procesAccess($this_id);
        if(isset($this_id)) {
            $row = $this->menu[$this_id];
            if ($row['position'] == 2) {
                \Yii::$app->session['leftmenu'] = $row['c'] . '-' . $row['a'];
            }
        }
        return parent::beforeAction($action);
    }

    private function  __procesAccess($this_id){

        if(\Yii::$app->controller->id!='site'){
            if(\Yii::$app->user->isGuest){//Returns a value indicating whether the user is a guest (not authenticated).
                header('location:'.Fun::url(['site/login']));exit();
                //return $this->redirectMessage('000000',Fun::url(['site/login']));
            } elseif(\Yii::$app->user->identity->role!='admin'&&!\Yii::$app->user->can(Fun::getPermissionStr(Fun::cache('menu_branch_cache',false)[$this_id]))){
                throw new BadRequestHttpException('您无权限操作！');
            }
        }
    }

    public function redirectMessage($message,$url='', $is_dialog=true, $param=[],$str='',$status='success', $delay=1){
        if($is_dialog){
            $this->layout=false;
        }
        return $this->render('@app/views/layouts/message.php',
            [
                'message'=> $message,
                'url'=> $url,
                'is_dialog'=>$is_dialog,
                'param'=>$param,
                'str'=>$str,
                'status'=> $status,
                'delay'=> $delay,
            ]
        );
    }

}